<?php 
	//header("Content-type: text");
	//ini_set('display_errors', 1);
	include_once('lib/simple_html_dom.php');
	
	require "Twitter/index.php";
	require "Tumblr/blogRead.php";
	require "Facebook/index.php";
	require "Instagram/index.php";
	require "RSS/index_young.php";
    include("mysql_connect.php");
	include("error/upload.php");
	
	session_start();
	
// Get PageIdx / PageNum / Search Key
	//$xml = simplexml_load_file('php://input');
//	$xml = simplexml_load_file('StreamA.xml');
	$xml = simplexml_load_string('<Stream Pages="10" PageIndex="1" Color="" Tags="" Location=""><googleReader feed="http://www.lottieanddoof.com" /></Stream>');
	
//	var_dump('php://input');
	
//	$input = file_get_contents('php://input');
// replace & followed by a bunch of letters, numbers
// and underscores and an equal sign with &amp;
//$input = preg_replace('#&(?=[a-z_0-9]+=)#', '&amp;', $input);
//$xml = simplexml_load_file($input);
	//print_r($xml);
	foreach( $xml->attributes( ) as $attr)
	{
		$AttrArray[] = $attr;
	}
	$nMaxNum = $AttrArray[0];
	$nPageIdx= $AttrArray[1];
	//$nPageIdx = $_POST['XMLidx'];
	$nItemIdx = ($nPageIdx - 1) * $nMaxNum;
	$strCategory = $AttrArray[2];
	$strColor = $AttrArray[2];
	$strTag = $AttrArray[3];
	$nLocation = $AttrArray[4];
	
	//$TwitterAcc = $xml->children();
	foreach( $xml->children() as $child)
	{
		switch ($child->getName())
		{
			case "bespoke":
				foreach( $child->attributes( ) as $attr)
					$Bespoke[] = (string)$attr;
				$UserName = $Bespoke[0];
				break;
			case "facebook":
				foreach( $child->attributes( ) as $attr)
					$Facebook[] = (string)$attr;
				break;
			case "twitter":
				foreach( $child->attributes( ) as $attr)
					$Twitter[] = (string)$attr;
				break;
			case "tumblr":
				foreach( $child->attributes( ) as $attr)
					$Tumblr[] = (string)$attr;
				break;
			case "instagram":
				foreach( $child->attributes( ) as $attr)
					$Instagram[] = (string)$attr;
				break;
			case "googleReader":
				foreach( $child->attributes( ) as $attr)
					$GoogleReader[] = (string)$attr;
				break;
		}
	}
	
	$response = new Response();
	$response->renderExceptions(true);
	
	if( $nItemIdx == 0 )
	{
		session_unset ( );
		$_SESSION['feedNum']=1;
		// Get Each queue = getItem( 0, PageNum )
// 		if(isset($Bespoke) && strlen($Bespoke[0]) > 0)
// 		{
// 			set_error_handler("My_ErrorHandler");//Processed php error.
					 
// 			try {// Action code
// 				$_SESSION['QBeSpoke'] = GetDataFromSQL( $nItemIdx, $nMaxNum, $strCategory, $strColor, $strTag, $nLocation, $UserName );
// 			} catch (Exception $e) {
// 				$returnValue = 0;
//     			$response->setException($e); //Collect exception.
// 		    }
// 		}
// 		if(isset($Facebook) && strlen($Facebook[0]) > 0)
// 		{
// 			set_error_handler("My_ErrorHandler");//Processed php error.
					 
// 			try {// Action code
// 				$_SESSION['QFacebook'] = GetFacebookMedia( Array('limit'=>$nMaxNum,'Access_id'=>$Facebook[0],'Access_token'=>$Facebook[1],'Reset'=>'true'));
// 			} catch (Exception $e) {
// 				$returnValue = 0;
//     			$response->setException($e); //Collect exception.
// 		    }
// 		}
// 		if(isset($Twitter) && strlen($Twitter[0]) > 0)
// 		{
// 			set_error_handler("My_ErrorHandler");//Processed php error.
					 
// 			try {// Action code
// 				$_SESSION['QTwitter'] = GetTwitterMedia( Array("twitter_count"=>$nMaxNum,'Access_token'=>$Twitter[0],'Access_token_secret'=>$Twitter[1],'Reset'=>'true'));
// 			} catch (Exception $e) {
// 				$returnValue = 0;
//     			$response->setException($e); //Collect exception.
// 		    }
// 		}
// 		if(isset($Tumblr)&& strlen($Tumblr[0]) > 0)
// 		{
// 			set_error_handler("My_ErrorHandler");//Processed php error.
					 
// 			try {// Action code
// 				$_SESSION['QTumblr'] = GetTumblrMedia( Array('limit'=>$nMaxNum,'uname'=>$Tumblr[0],'Reset'=>'true'));
// 			} catch (Exception $e) {
// 				$returnValue = 0;
//     			$response->setException($e); //Collect exception.
// 		    }
// 		}
// 		if(isset($Instagram)&& strlen($Instagram[0]) > 0)
// 		{
// 			set_error_handler("My_ErrorHandler");//Processed php error.
					 
// 			try {// Action code
// 				$_SESSION['QInstagram'] = GetInstagramMedia( Array('limit'=>$nMaxNum,'Access_Token'=>$Instagram[0],'Reset'=>'true'));
// 			} catch (Exception $e) {
// 				$returnValue = 0;
//     			$response->setException($e); //Collect exception.
// 		    }
// 		}
		if(isset($GoogleReader)&& strlen($GoogleReader[0]) > 0)
		{
			set_error_handler("My_ErrorHandler");//Processed php error.
					 
			try {// Action code
				$_SESSION['QRSS'] = GetRSSMedia($GoogleReader,$nMaxNum);//GetRSSMedia from index.php function call
				unset($_SESSION['old']);
				$_SESSION['old']=$_SESSION['QRSS'];
			} catch (Exception $e) {
				$returnValue = 0;
    			$response->setException($e); //Collect exception.
		    }
		}
		// each QEnd = PageNum
		$_SESSION['QEnd'] = array( "BeSpoke"=>(int)$nMaxNum, "Facebook"=>$nMaxNum+1, "Twitter"=>$nMaxNum+1, "Tumblr"=>(int)$nMaxNum, "Instagram"=>$nMaxNum+1 );
	}
// else 
	else
	{
		
	// if each QLength < PageNum
		//queue += getItem( QEnd, PageNum )
		//QEnd += PageNum
		if(isset($Bespoke) && strlen($Bespoke[0]) > 0 )
		{
			if( count($_SESSION['QBeSpoke']) < $nMaxNum)
			{
				set_error_handler("My_ErrorHandler");//Processed php error.
					 
				try {// Action code
					$_SESSION['QBeSpoke'] = array_merge($_SESSION['QBeSpoke'], GetDataFromSQL( $_SESSION['QEnd']['BeSpoke'], $nMaxNum, $strCategory, $strColor, $strTag, $nLocation, $UserName ));
					$_SESSION['QEnd']['BeSpoke'] += $nMaxNum;
				} catch (Exception $e) {
					$returnValue = 0;
    				$response->setException($e); //Collect exception.
		 	    }
			}
		}
		if( isset($Facebook) && strlen($Facebook[0]) > 0 )
		{ 
			if(count($_SESSION['QFacebook']) < $nMaxNum)
			{
				set_error_handler("My_ErrorHandler");//Processed php error.
					 
				try {// Action code
					$_SESSION['QFacebook'] = array_merge($_SESSION['QFacebook'], GetFacebookMedia( Array('limit'=>$nMaxNum,'Access_id'=>$Facebook[0],'Access_token'=>$Facebook[1],'Reset'=>'false')));
					$_SESSION['QEnd']['Facebook'] += $nMaxNum;
				} catch (Exception $e) {
					$returnValue = 0;
    				$response->setException($e); //Collect exception.
		 	    }
			}	
		}	
		if( isset($Twitter) && strlen($Twitter[0]) > 0 )
		{ 
			if(count($_SESSION['QTwitter']) < $nMaxNum/*&& isset($Twitter)*/)
			{
				set_error_handler("My_ErrorHandler");//Processed php error.
					 
				try {// Action code
					$_SESSION['QTwitter'] = array_merge($_SESSION['QTwitter'], GetTwitterMedia( Array("twitter_count"=>$nMaxNum,'Access_token'=>$Twitter[0],'Access_token_secret'=>$Twitter[1],'Reset'=>'false')));
					$_SESSION['QEnd']['Twitter'] += $nMaxNum;
				} catch (Exception $e) {
					$returnValue = 0;
    				$response->setException($e); //Collect exception.
		 	    }
			}	
		}
		if( isset($Tumblr) && strlen($Tumblr[0]) > 0 )
		{ 
			if(count($_SESSION['QTumblr']) < $nMaxNum)
			{
				set_error_handler("My_ErrorHandler");//Processed php error.
					 
				try {// Action code
					$_SESSION['QTumblr'] = array_merge($_SESSION['QTumblr'], GetTumblrMedia( Array('limit'=>$nMaxNum,'uname'=>$Tumblr[0],'Reset'=>'false')));
					$_SESSION['QEnd']['Tumblr'] += $nMaxNum;
				} catch (Exception $e) {
					$returnValue = 0;
    				$response->setException($e); //Collect exception.
		 	    }
			}	
		}
		if( isset($Instagram) && strlen($Instagram[0]) > 0 )
		{ 
			if(count($_SESSION['QInstagram']) < $nMaxNum)
			{
				set_error_handler("My_ErrorHandler");//Processed php error.
					 
				try {// Action code
					$_SESSION['QInstagram'] = array_merge($_SESSION['QInstagram'], GetInstagramMedia( Array('limit'=>$nMaxNum,'Access_Token'=>$Instagram[0],'Reset'=>'false')));
					$_SESSION['QEnd']['Instagram'] += $nMaxNum;
				} catch (Exception $e) {
					$returnValue = 0;
    				$response->setException($e); //Collect exception.
		 	    }
			}	
		}
		
		if(isset($GoogleReader)&& strlen($GoogleReader[0]) > 0)
		{  
			/**
			 * @param $nMaxNum is how many info you want to show in a page.
			 */
			$maxItems=($_SESSION['feedNum']+1)*$nMaxNum;
			
			$newArray=GetRSSMedia($GoogleReader,$maxItems);
			$returnArray=array();
			if(isset($_SESSION['old'])){
				/**
				 * @todo make $returnArray 
				 * 
				 */
				
 				foreach($newArray as $n){
 					$check=0;
					foreach ($_SESSION['old'] as $o){
						if($n[0]['BeMediaID']==$o[0]['BeMediaID']){
							
							$check++;
						}
						
					}
					echo $check;
					if($check==0){
						array_push($returnArray,$n);
					}
					
 				}
				
 				print_r($returnArray);
 				
				//update old list
				$_SESSION['old']=$newArray;
				
				$_SESSION['QRSS']=$returnArray;//$_SESSION['QRSS'] is really for <MediaLists> tag. 
				//print_r($newArray);
			}else{
				$_SESSION['old']='llll';
				echo 'OKOKOK';
			}
			$_SESSION['feedNum']++;
		}
	}
	
	echo '<MediaLists>';		
// pop new (n) Item from queues to Output
	for( $i = 0 ; $i < $nMaxNum ; $i++ )
	{
		unset($strKey);
		$Time = 0;
//		Max( $QBeSpoke, $QFacebook, $QTwitter, $QTumblr, $QInstagram);
		try {// Action code
			
			if( !empty($_SESSION['QBeSpoke']) )
			{
				$strKey = 'QBeSpoke';
				$Time = $_SESSION['QBeSpoke'][0][0]['lastUpdate'];
			}
		} catch (Exception $e) {
			$returnValue = 0;
   			$response->setException($e); //Collect exception.
		}
		
		try {// Action code
			if( !empty($_SESSION['QFacebook']) && $_SESSION['QFacebook'][0][0]['lastUpdate'] > $Time)
			{
				$strKey = 'QFacebook';
				$Time = $_SESSION['QFacebook'][0][0]['lastUpdate'];
			}
		} catch (Exception $e) {
			$returnValue = 0;
   			$response->setException($e); //Collect exception.
		}
		
		try {// Action code
			if( !empty($_SESSION['QTwitter']) && $_SESSION['QTwitter'][0][0]['lastUpdate'] > $Time )
			{
				$strKey = 'QTwitter';
				$Time = $_SESSION['QTwitter'][0][0]['lastUpdate'];
			}
		} catch (Exception $e) {
			$returnValue = 0;
   			$response->setException($e); //Collect exception.
		}
		
		try {// Action code
			if( !empty($_SESSION['QTumblr']) && $_SESSION['QTumblr'][0][0]['lastUpdate'] > $Time )
			{
				$strKey = 'QTumblr';
				$Time = $_SESSION['QTumblr'][0][0]['lastUpdate'];
			}
		} catch (Exception $e) {
			$returnValue = 0;
   			$response->setException($e); //Collect exception.
		}
		
		try {// Action code
			if( !empty($_SESSION['QInstagram']) && $_SESSION['QInstagram'][0][0]['lastUpdate'] > $Time )
			{
				$strKey = 'QInstagram';
				$Time = $_SESSION['QInstagram'][0][0]['lastUpdate'];
			}
		} catch (Exception $e) {
			$returnValue = 0;
   			$response->setException($e); //Collect exception.
		}
		
		try {// Action code
			if( !empty($_SESSION['QRSS']) && $_SESSION['QRSS'][0][0]['lastUpdate'] > $Time )
			{
				$strKey = 'QRSS';
				$Time = $_SESSION['QRSS'][0][0]['lastUpdate'];
			}
		} catch (Exception $e) {
			$returnValue = 0;
   			$response->setException($e); //Collect exception.
		}
		
		if( !isset($strKey) )
		{
			break;
		}
//		$Output = array_shift( $QMax );

		try {// Action code	
			$Output = array_shift( $_SESSION[$strKey] );
			OutputXMLFormat( $Output );
		} catch (Exception $e) {
			$returnValue = 0;
   			$response->setException($e); //Collect exception.
		}
	}
	echo '</MediaLists>';	
	
	function GetDataFromSQL( $start, $num, $Category, $Color, $Tag, $Location, $UserName )
	{
		$MediaList = array();
		
		$strSqlCommand = "SELECT idUSER FROM user WHERE Email = '".$UserName."'";
		$result = mysql_query($strSqlCommand);
		$rowUserInfo = @mysql_fetch_array($result);		

		$strSqlCommand = "SELECT MediaDownloadPath FROM Global_Config WHERE 1";
		$result = mysql_query($strSqlCommand);
		$row = @mysql_fetch_array($result);	
		$ServerPath = $row['MediaDownloadPath'];
 //var_dump($ServerPath);   
		// Search Media Table with 4 Tables' Name
    	
		/**if(($Channel != "All Bespoke")&&($Channel != "Show All")&&($Channel != "")) {
			
			if($Category != ""){
				$strSqlCommand = "SELECT idMEDIA, MEDIA_TYPE_idMEDIA_TYPE, WebLink, ModifyTime, tbMed.Enable 
						FROM MEDIA tbMed
						LEFT JOIN SPOT_CY_MEDIA tbCatM	ON 	tbMed.idMEDIA = tbCatM.MEDIA_idMEDIA
						LEFT JOIN CATEGORY tbCat		ON 	tbCat.idCATEGORY = tbCatM.CATEGORY_idCATEGORY
						LEFT JOIN COLOR tbCol			ON 	tbCol.idCOLOR = tbMed.COLOR_idCOLOR 
						LEFT JOIN LOCATION tbLoc		ON 	tbMed.LOCATION_idLOCATION = tbLoc.idLOCATION
						LEFT JOIN ZIPCODE tbZip 		ON 	tbLoc.ZIPCODE_idZIPCODE = tbZip.idZIPCODE 
						LEFT JOIN CHANNELS tbCha	    ON 	tbCat.CHANNELS_idCHANNELS = tbCha.idCHANNELS ";//";
			}
			else {
				$strSqlCommand = "SELECT idMEDIA, MEDIA_TYPE_idMEDIA_TYPE, WebLink, ModifyTime, tbMed.Enable 
						FROM MEDIA tbMed
						LEFT JOIN COLOR tbCol			ON 	tbCol.idCOLOR = tbMed.COLOR_idCOLOR
						LEFT JOIN SPOT_TAG_MEDIA tbTagM	ON 	tbMed.idMEDIA = tbTagM.MEDIA_idMEDIA
						LEFT JOIN TAGS tbTag			ON 	tbTag.idTAGS = tbTagM.TAGS_idTAGS
						LEFT JOIN LOCATION tbLoc		ON 	tbMed.LOCATION_idLOCATION = tbLoc.idLOCATION
						LEFT JOIN ZIPCODE tbZip 		ON 	tbLoc.ZIPCODE_idZIPCODE = tbZip.idZIPCODE
						LEFT JOIN SPOT_CY_MEDIA tbCatM 	ON 	tbMed.idMEDIA = tbCatM.MEDIA_idMEDIA
						LEFT JOIN CATEGORY tbCat        ON 	tbCat.idCATEGORY = tbCatM.CATEGORY_idCATEGORY
						LEFT JOIN CHANNELS tbCha        ON 	tbCha.idCHANNELS = tbCat.CHANNELS_idCHANNELS ";//";
			}
		}**/
        if($Category != "") {
        	$strSqlCommand = "SELECT idMEDIA, MEDIA_TYPE_idMEDIA_TYPE, WebLink, ModifyTime, tbMed.Enable 
						FROM MEDIA tbMed
						LEFT JOIN SPOT_CY_MEDIA tbCatM	ON 	tbMed.idMEDIA = tbCatM.MEDIA_idMEDIA
						LEFT JOIN CATEGORY tbCat		ON 	tbCat.idCATEGORY = tbCatM.CATEGORY_idCATEGORY
						LEFT JOIN COLOR tbCol			ON 	tbCol.idCOLOR = tbMed.COLOR_idCOLOR 
						LEFT JOIN LOCATION tbLoc		ON 	tbMed.LOCATION_idLOCATION = tbLoc.idLOCATION
						LEFT JOIN ZIPCODE tbZip 		ON 	tbLoc.ZIPCODE_idZIPCODE = tbZip.idZIPCODE ";//";
        }
		else {
        	$strSqlCommand = "SELECT DISTINCT idMEDIA, MEDIA_TYPE_idMEDIA_TYPE, WebLink, ModifyTime, tbMed.Enable
						FROM MEDIA tbMed 
						LEFT JOIN SPOT_TAG_MEDIA tbTagM	ON 	tbMed.idMEDIA = tbTagM.MEDIA_idMEDIA
						LEFT JOIN COLOR tbCol			ON 	tbCol.idCOLOR = tbMed.COLOR_idCOLOR
						LEFT JOIN TAGS tbTag			ON 	tbTag.idTAGS = tbTagM.TAGS_idTAGS
						LEFT JOIN LOCATION tbLoc		ON 	tbMed.LOCATION_idLOCATION = tbLoc.idLOCATION
						LEFT JOIN ZIPCODE tbZip 		ON 	tbLoc.ZIPCODE_idZIPCODE = tbZip.idZIPCODE  ";//";
        }
		
		$strSqlCommand .="WHERE tbMed.Enable = 0 AND tbMed.BeMedia_SocialID IS NULL ";
		
		if( strlen($Category) > 0 )
			$strSqlCommand .= "AND tbCat.Name = '$Category' ";
			 
		if( strlen($Color) > 0 )
			$strSqlCommand .= "AND tbCol.Name = '$Color' ";
	
		if( strlen($Tag) > 0 )
			$strSqlCommand .= "AND tbTag.Name = '$Tag' ";
	
		if( strlen($Location) > 0 )
		{
			if (strlen((int)$Location)==5)
				$strSqlCommand .= "AND tbZip.ZipCode = '$Location' ";
			else
				$strSqlCommand .= "AND tbLoc.Address like '%$Location%' ";
		}
     
		$strSqlCommand .= " ORDER BY ModifyTime DESC LIMIT $start, $num ";
		
		 //echo $strSqlCommand;
		// Get Media Item List
		$result = mysql_query($strSqlCommand);
//echo ($strSqlCommand);	var_dump($result);	
		
		while($rowMedia = @mysql_fetch_array($result))	
		{
			$Media = array();
//var_dump($rowMedia);			
			// Get Comment Count
			$nID = $rowMedia['idMEDIA'];
			/**$strSqlCommand = "SELECT * FROM COMMENTS 
							  LEFT JOIN USER ON COMMENTS.USER_idUSER = USER.idUSER 
							  WHERE MEDIA_idMEDIA = '$nID'";**/
							  
			$strSqlCommand = "SELECT idCOMMENTS, Comment, USER.Name
									FROM COMMENTS
									LEFT JOIN USER           ON COMMENTS.USER_idUSER = USER.idUSER
									LEFT JOIN sharegroup     ON USER.idUSER = sharegroup.USER_idUSER
									LEFT JOIN spot_group_users tbGU   ON sharegroup.idGROUP = tbGU.GROUP_idGROUP
							  		WHERE MEDIA_idMEDIA = '".$nID."' AND tbGU.USER_idUSER=".$rowUserInfo['idUSER']."
									OR MEDIA_idMEDIA = '".$nID."' AND sharegroup.USER_idUSER=".$rowUserInfo['idUSER']."
									OR MEDIA_idMEDIA = '".$nID."' AND USER.idUSER=".$rowUserInfo['idUSER']." GROUP BY idCOMMENTS";
			$resultComment = mysql_query($strSqlCommand); 
			$nCommentCount = @mysql_num_rows($resultComment);
			
			// Get Media Type
			$nTypeID = $rowMedia['MEDIA_TYPE_idMEDIA_TYPE'];
			$strSqlCommand = "SELECT Name FROM MEDIA_TYPE WHERE idMEDIA_TYPE = '$nTypeID'";
			$resultMediaType = mysql_query($strSqlCommand);	
			$rowMediaType = @mysql_fetch_array($resultMediaType);
		
			if($nTypeID == 8){
				$RssMediaDetial = array( "Head"=>"Media", "ID"=>$nID, "MediaType"=>$rowMediaType['Name'], "CommentCount"=>$nCommentCount, 
						"WebLink"=>/*$rowMedia['ModifyTime']/*/$rowMedia['WebLink'], "Source"=>"Bespoke", "Author"=>"" ,"lastUpdate"=>strtotime($rowMedia['ModifyTime']));
				
				array_push( $Media, $RssMediaDetial );
				
				$resultMediaType = mysql_query($strSqlCommand);	
				$rowMediaType = @mysql_fetch_array($resultMediaType);
				
				// Get GoogleReader Data
				$strSqlCommand = "SELECT * FROM TEXT tbText 
								  LEFT JOIN IMAGE tbImage	ON tbText.MEDIA_idMEDIA = tbImage.MEDIA_idMEDIA
								  WHERE tbText.MEDIA_idMEDIA = '$nID'";
				 
				$resultText = mysql_query($strSqlCommand);	
				while($rowText = mysql_fetch_array($resultText))
				{
					$MediaDetial = array( "Head"=>"beHtml", "ThumbnailImage"=>$rowText['FileName'], "ThumbnailWidth"=>$rowText['Width'], "ThumbnailHeight"=>$rowText['Height'], "Title"=>$rowText['Title'], "Description"=>$rowText['Description']);
					array_push( $Media, $MediaDetial );
				}  
			}
			else{
				$MediaDetial = array( "Head"=>"Media", "ID"=>$nID, "MediaType"=>$rowMediaType['Name'], "CommentCount"=>$nCommentCount, 
				"WebLink"=>/*$rowMedia['ModifyTime']/*/$rowMedia['WebLink'], "Source"=>"Bespoke", "Author"=>"" ,"lastUpdate"=>strtotime($rowMedia['ModifyTime']));//
				array_push( $Media, $MediaDetial );
	
				// Get Text Data
				$strSqlCommand = "SELECT * FROM TEXT WHERE MEDIA_idMEDIA = '$nID'";
				$resultText = mysql_query($strSqlCommand);	
				while($rowText = mysql_fetch_array($resultText))
				{
					$MediaDetial = array( "Head"=>"Text", "ID"=>$rowText['idText'], "Title"=>$rowText['Title'], "Description"=>$rowText['Description']);
					array_push( $Media, $MediaDetial );
				}
			
				// Get Image Data
				$strSqlCommand = "SELECT * FROM IMAGE WHERE MEDIA_idMEDIA = '$nID'";
				$resultImage = mysql_query($strSqlCommand);	
				while($rowImage = mysql_fetch_array($resultImage))
				{
					if( $rowImage['Type'] == "URL" )
					{
						$MediaDetial = array( "Head"=>"Image_W_H", "ID"=>$rowImage['idIMAGE'], "Type"=>$rowImage['Type'],
					 							"Width"=>$rowImage['Width'], "Height"=>$rowImage['Height'], "FileName"=>$rowImage['FileName'], 
												"Description"=>"");
					}
					else
					{
						$MediaDetial = array( "Head"=>"Image_W_H", "ID"=>$rowImage['idIMAGE'], "Type"=>$rowImage['Type'],
					 							"Width"=>$rowImage['Width'], "Height"=>$rowImage['Height'], "FileName"=>$ServerPath.$nID."/".$rowImage['FileName'], 
												"Description"=>"");
					}
					array_push( $Media, $MediaDetial );
					
					$nImageID = $rowImage['idIMAGE'];
					 
					// Get Note Data
					/*$strSqlCommand = "SELECT * FROM notes WHERE MEDIA_idMEDIA=' $nID'";
					$resultNote = mysql_query($strSqlCommand);
					
					if(mysql_num_rows($resultNote)!=0) {
						$MediaDetial = array( "Head"=>"Image_End", "End"=>">");
						array_push( $Media, $MediaDetial );
					}
					
					while($rowNote = mysql_fetch_array($resultNote))
					{
						$MediaDetial = array( "Head"=>"Note", "ID"=>$rowNote['idNOTES'], "Text"=>$rowNote['NoteText'],
					 							"AxisX"=>$rowNote['AxisX'], "AxisY"=>$rowNote['AxisY']);
												
						array_push( $Media, $MediaDetial );
					}
					
					if(mysql_num_rows($resultNote)!=0)
						$MediaDetial = array( "Head"=>"Image_End", "End"=>"</Image>");
					else
						$MediaDetial = array( "Head"=>"Image_End", "End"=>"/>");
					array_push( $Media, $MediaDetial );*/
					
					//$MediaDetial = array( "Head"=>"Image_End", "End"=>"</Image>");
					//array_push( $Media, $MediaDetial );
				}
			
				// Get Video Data
				$strSqlCommand = "SELECT * FROM Video WHERE MEDIA_idMEDIA = '$nID'";
				$resultVideo = mysql_query($strSqlCommand);	
				while($rowVideo = mysql_fetch_array($resultVideo))
				{
					if( $rowVideo['Type'] == "URL" )
					{
						$MediaDetial = array( "Head"=>"Video", "ID"=>$rowVideo['idVideo'], "Type"=>$rowVideo['Type'],
					 							"FileName"=>$rowVideo['FileName'], "Description"=>"");
					}
					else
					{				
						$MediaDetial = array( "Head"=>"Video", "ID"=>$rowVideo['idVideo'], "Type"=>$rowVideo['Type'],
					 							"FileName"=>$ServerPath.$nID."/".$rowVideo['FileName'], "Description"=>"");
					}
					array_push( $Media, $MediaDetial );
				} 
			} 
			
			while($rowComment = @mysql_fetch_array($resultComment)){
		        		$Mediae = array( "Head"=>"Comment", "ID"=>$rowComment['idCOMMENTS'], "Content"=>$rowComment['Comment'], "User"=>$rowComment['Name']);
						array_push( $Media, $Mediae );
		    }
 			
			
			$strSqlCommand = "SELECT idNOTES, NoteText, AxisX, AxisY
						  		FROM notes 
								LEFT JOIN USER                       ON NOTES.USER_idUSER = USER.idUSER 
								LEFT JOIN sharegroup                 ON USER.idUSER = sharegroup.USER_idUSER
								LEFT JOIN spot_group_users tbGU      ON sharegroup.idGROUP = tbGU.GROUP_idGROUP
								WHERE notes.MEDIA_idMEDIA = '".$nID."' AND tbGU.USER_idUSER=".$rowUserInfo['idUSER']."
								OR notes.MEDIA_idMEDIA = '".$nID."' AND sharegroup.USER_idUSER=".$rowUserInfo['idUSER']." 
								OR notes.MEDIA_idMEDIA = '".$nID."' AND USER.idUSER=".$rowUserInfo['idUSER']." GROUP BY idNOTES";
			//$strSqlCommand = "SELECT * FROM notes WHERE MEDIA_idMEDIA = '$nID'";
			$resultNote = mysql_query($strSqlCommand);
			
			while($rowNote = mysql_fetch_array($resultNote))
			{
						$MediaDetial = array( "Head"=>"Note", "ID"=>$rowNote['idNOTES'], "Text"=>$rowNote['NoteText'],
					 							"AxisX"=>$rowNote['AxisX'], "AxisY"=>$rowNote['AxisY']);
												
						array_push( $Media, $MediaDetial );
			}
					 
			array_push ($MediaList, $Media);
    	}
		
		return $MediaList;
	}
	
	if ($response->isException()) {//Exception record.
	}
	$response->sendResponse(); // Display All result(contain Header, Exception, Body, etc)
	
	
	
	function OutputXMLFormat( $OutputData )
	{ 
		foreach( $OutputData as $OutputRow)
		{ 
			switch($OutputRow['Head'])
			{
				case "Media":
					if(isset($OutputRow['BeMediaID']))
					{
						echo '<Media ID="'.$OutputRow['ID'].'" BeMediaID="'.$OutputRow['BeMediaID'].'" MediaType="'.$OutputRow['MediaType'].'" CommentCount="'.$OutputRow['CommentCount'].
						'" WebLink="'.XMLCharEncode($OutputRow['WebLink']).'" Source="'.$OutputRow['Source'].'" Author="'.XMLCharEncode($OutputRow['Author']).'" lastUpdate="'.date("Y-m-d",($OutputRow['lastUpdate'])).'" >';
					}
					else
					{
						echo '<Media ID="'.$OutputRow['ID'].'" BeMediaID="" MediaType="'.$OutputRow['MediaType'].'" CommentCount="'.$OutputRow['CommentCount'].
						'" WebLink="'.XMLCharEncode($OutputRow['WebLink']).'" Source="'.$OutputRow['Source'].'" Author="'.XMLCharEncode($OutputRow['Author']).'" lastUpdate="'.date("Y-m-d",($OutputRow['lastUpdate'])).'" >';
					}
					break;
				case "Text":
						echo '<Text ID="'.$OutputRow['ID'].'" Title="'.XMLCharEncode($OutputRow['Title']).'" Description="'.XMLCharEncode($OutputRow['Description']).'" ></Text>';
					break;
				case "Image":
					echo '<Image ID="'.$OutputRow['ID'].'" Type="'.$OutputRow['Type'].'" FileName="'.$OutputRow['FileName'].'" Description="'.XMLCharEncode($OutputRow['Description']).'" />';
					break;
				case "Image_W_H":
					echo '<Image ID="'.$OutputRow['ID'].'" Type="'.$OutputRow['Type'].'" Width="'.$OutputRow['Width'].'" Height="'.$OutputRow['Height'].'" FileName="'.$OutputRow['FileName'].'" Description="'.XMLCharEncode($OutputRow['Description']).'" />';
					break;	
				case "Image_End":
					echo $OutputRow['End'];
					break;
				case "Video":
					echo '<Video ID="'.$OutputRow['ID'].'" Type="'.$OutputRow['Type'].'" FileName="'.$OutputRow['FileName'].'" Description="'.XMLCharEncode($OutputRow['Description']).'" />';
					break;
				case "beHtml":
						
						$str = $OutputRow['Description'];
						if($str != ""){
							$html = str_get_html($str);
						 
							foreach($html->find('a') as $e){
								foreach($e->find('img') as $d)
									$str = str_replace($e->href, "#", $str);
							} 
						} 
						
						if(isset($OutputRow['ThumbnailImage'])){
							echo '<beHtml ThumbnailImage="'.$OutputRow['ThumbnailImage'].'" ThumbnailWidth="'.$OutputRow['ThumbnailWidth'].'" ThumbnailHeight="'.$OutputRow['ThumbnailHeight'].'" Title="'.XMLCharEncode($OutputRow['Title']).'" Description="'.XMLCharEncode($str).'" />';
						}else{
							echo '<beHtml Title="'.XMLCharEncode($OutputRow['Title']).'" Description="'.XMLCharEncode($str).'" />';
						} 
						 
					break;
				case "Note": 
					echo '<Note ID="'.$OutputRow['ID'].'" Text="'.XMLCharEncode($OutputRow['Text']).'" AxisX="'.$OutputRow['AxisX'].'" AxisY="'.$OutputRow['AxisY'].'" ></Note>';
					break;
				case "Comment":
					echo '<Comment ID="'.$OutputRow['ID'].'" Content="'.XMLCharEncode($OutputRow['Content']).'" User="'.XMLCharEncode($OutputRow['User']).'"></Comment>';
					break;
				default:
					echo '<Error Title="Tag Error" />';
			}
		}
		echo '</Media>';
	}
	
	function XMLCharEncode( $Subject )
	{
		$Serach  = array( "<", ">", "&", "'","\"" );
		$Replace = array( "&lt;","&gt;","&amp;","&apos;","&quot;");
		return str_replace($Serach, $Replace, $Subject);
	}
	
	
	
function My_ErrorHandler($errno, $errstr, $errfile, $errline )
{
	throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}

class Response
{
    private $_exceptions = array();
    private $_renderExceptions = false;
    public function setException(Exception $e)
    {
        $this->_exceptions[] = $e;
    }
    public function getExceptions()
    {
        return $this->_exceptions;
    }
    public function isException()
    {
        return !empty($this->_exceptions);
    }
    public function renderExceptions($flag = null)
    {
        if (null !== $flag) {
            $this->_renderExceptions = $flag ? true : false;
        }
        return $this->_renderExceptions;
    }
    public function sendResponse()
    {
        //echo "Header sending...\n";
        $exception = '';
        if ($this->isException() && $this->renderExceptions()) {
            foreach ($this->getExceptions() as $e) {
                $exception .= $e->getMessage() . "\n";
            }
			
			saveError_Feed("Stream", "", date("Y-m-d H:i:s"), $exception);
        }
        //echo "Body sending...\n";
    }
}
	
	
?>